<template>
	<el-form :inline="true" size="small">
	    
	
	    <el-form-item label="部门">
	        <el-select v-model="query.dId" style="width:100px;" @change="getPage(1)">
	            <el-option label="全部" value="" />
	            <el-option v-for="item in depList" :key="item.did" :label="item.dname" :value="item.did" />
	        </el-select>
	    </el-form-item>
	
	
	    <el-form-item>
	        <el-button :icon="Search" type="primary" @click="getPage(1)" >查询</el-button>
	        <el-button :icon="Plus" type="primary" @click="signAddRef.open(depList)" >新增</el-button>
	        <el-button :icon="Delete" type="danger" @click="execMultiDel" >删除</el-button>
	        
	    </el-form-item>
	</el-form>
	
	
	<el-table :data="page.records" @selection-change="onSelectionChange" >
	    <el-table-column type="selection"/>
	    <el-table-column prop="depId" label="部门" >
	        <template #default="{row}">
	            {{ row.depId }}
	        </template>
	    </el-table-column>
	    <el-table-column prop="clockTime" label="签到时间" />
		<el-table-column prop="clockOutTime" label="签退时间" />
		<el-table-column prop="clockRange" label="签到范围">
		    <template #default="{row}">
		        {{ row.clockRange }} 米
		    </template>
		</el-table-column>
		<el-table-column label="地理位置">
		      <template #default="{row}">
		        {{ row.location || '获取中...' }}
		      </template>
		    </el-table-column>
	    
	   
	    <el-table-column label="操作">
	        <template #default="{row}">
	            <el-button size="small" @click="signUpdRef.open(depList,row)" >修改</el-button>
	            <el-button type="danger" size="small" @click="signDel(row.id)" >删除</el-button>
	        </template>         
	    </el-table-column>
	</el-table>
	
	<!-- 分页组件 -->
	<el-pagination style="margin-top:5px;"
	    :page-sizes="[2,3,5,10,15,20,30,100]"
	    layout="sizes,prev,pager,next,jumper,->,total"
	    :total="page.total" 
	    v-model:page-size="query.pageSize" 
	    v-model:current-page="query.pageNum" 
	    @current-change="getPage"
	    @size-change="getPage(1)"
	    />
	
	<!-- 新增打卡信息 -->
	<sign-add ref="signAddRef" @add-ok="getPage(1)"></sign-add>
	
	<!-- 打卡信息修改-->
	<sign-upd ref="signUpdRef" @upd-ok="getPage(page.current)"></sign-upd>
	
</template>

<script setup>
	import { ref, reactive } from 'vue'
	import req from '@/request'
	import { Search, Plus, Delete } from '@element-plus/icons-vue';
	import { ElMessage, ElMessageBox } from 'element-plus'
	
	//新增
	import SignAdd from './SignAdd.vue'
	const signAddRef = ref(null);
	
	//修改
	import SignUpd from './SignUpd.vue'
	const signUpdRef = ref(null);
	
	const amapKey = '0d2cee1f7733f0cb68d49dd675ef9f43';
	
	const query = reactive({
	    pageNum: 1,
	    pageSize: 5,
	    dId: ''
	});
	
	const page = ref({
	    total: 0,//总记录数
	    list: []
	});
	
	const depList = ref([]);
	const getDepList = async () => {
	    const res = await req.get('/info/emp/dep');
	    depList.value = res.data;
	}
	getDepList();
	
	const getPage = async (pageNo = 1) => {
	    query.pageNum = pageNo;
	    const res = await req.post("/clock/list", query);
		const records = res.data.records;
		  
		  // 并行获取所有记录的地理位置
		  const promises = records.map(async record => {
		    try {
		      const location = await getAddress(record.latitude, record.longitude);
		      record.location = location;
		    } catch (error) {
		      console.error('获取地理位置失败:', error);
		      record.location = '未知地点';
		    }
		  });
		
		await Promise.all(promises);
	    page.value = res.data;
	
	    //使用获取的分页数据相关值覆盖 query.pageNum  和 query.pageSize
	    query.pageNum = page.value.current;
	    query.pageSize = page.value.size;
		console.log("pageNum:",query.pageNum)
		console.log("分页数据：",page.value)
	}
	getPage(1);
	
	// 新增地理位置获取方法
	const getAddress = async (lat, lng) => {
	  if (!lat || !lng) return '无坐标信息';
	  
	  const response = await fetch(
	    `https://restapi.amap.com/v3/geocode/regeo?key=${amapKey}&location=${lng},${lat}`
	  );
	  
	  const data = await response.json();
	  if (data.status === '1' && data.regeocode) {
		  console.log("位置：",data.regeocode.formatted_address)
	    return data.regeocode.formatted_address;
	  }
	  return '未知地点';
	};
	
	const signDel = async (id) => {
	  try {
	    await ElMessageBox.confirm(
	      "您确定要删除该打卡信息吗？",
	      "警告",
	      {
	        confirmButtonText: '确定删除',
	        cancelButtonText: '不删了',
	        type: 'warning'
	      }
	    );
	    
	    await req.get('/clock/delete/' + id);
	    getPage(page.value.current);
	    ElMessage.success('删除打卡信息成功！');
	  } catch (error) {
	    console.error('删除失败:', error);
	    ElMessage.error('删除打卡信息失败！');
	  }
	};
</script>

<style>
</style>